/*
 * PGN_Reader : A simple pgn reader for chess games.
 * Copyright (C) 2011 Laurent BERNABE
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gmail.bernabe.laurent.java_swing.pgn_reader.gui;

import java.awt.Dimension;
import java.util.ArrayList;

import javax.swing.JTextArea;

public class MovesJTextArea extends JTextArea {
	
	public MovesJTextArea(){
		setEditable(false);
		setPreferredSize(new Dimension(280, 300));
	}
	
	public void addHalfMove(String halfMove){
		moves.add(halfMove);
		updateDisplay();
	}
	
	public void undoLastHalfMove(){
		if (moves.size() > 0){
			moves.remove(moves.size() - 1);
			updateDisplay();
		}
	}
	
	private void updateDisplay() {
		/*
		 * 0 for white and 1 for black
		 */
		int currentPlayer = 0;
		int moveNumber = 1;
		
		setText("");
		setRows(0);
		invalidate();
		for (String currentMove : moves){
			StringBuilder textToDisplay = new StringBuilder();
			if (currentPlayer == WHITE) {
				setRows(getRows()+1);
				textToDisplay.append(String.format("%2d. ", moveNumber));
			}	
			
			textToDisplay.append(String.format("%20s ", currentMove));
			
			currentPlayer = 1 - currentPlayer;
			if (currentPlayer == WHITE) {
				moveNumber++;
				textToDisplay.append("\n");
			}
			invalidate();
			append(textToDisplay.toString());
		}
	}

	private ArrayList<String> moves = new ArrayList<String>();
	private static final long serialVersionUID = 1L;

	private final static int WHITE = 0;
}
